# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :jwt_generate.py
# @Time      :2022/6/8 20:04
# @Author    :张志坤

# 生成token
from flask_restful import current_app
from datetime import datetime, timedelta
from flask import g
import jwt


def generate_token(payload):
    # 获取盐
    secret = current_app.config.get("SECRET_KEY")
    # 设置过期时间
    expiry = datetime.utcnow() + timedelta(seconds=20)
    # 构建payload
    payload["expiry"] = '%s' % expiry
    # 生成token
    token = jwt.encode(payload, secret, algorithm='HS256')

    if g.is_refresh:
        exp = datetime.utcnow() + timedelta(days=15)
        payload['expiry'] = "%s" % exp
        refresh_token = jwt.encode(payload, secret, algorithm='HS256')
    else:
        refresh_token = None
    return token, refresh_token


# 校验token
def check_jwt(token):
    # 获取盐
    secret = current_app.config.get("SECRET_KEY")
    print("解码token的secret", secret)
    try:
        payload = jwt.decode(token, key=secret, algorithms=['HS256'])
        print("校验token 的payload", payload)
    except Exception as e:
        print("解码token报错", e)
        payload = None
    return payload
